package com.gzsxy.exception;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.gzsxy.cons.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 资源授权异常接入点-无效token
 * @date 2021/11/8 9:32
 */
public class AuthExceptionEntryPoint  implements AuthenticationEntryPoint {



    @Override
    public void commence(HttpServletRequest req, HttpServletResponse res, AuthenticationException authException) throws IOException, ServletException {

        Map<String, Object> map = new HashMap<>();

        //自定义信息
        Throwable cause = authException.getCause();
        //当token错误时
        if (cause instanceof InvalidTokenException){
            map.put("code", HttpStatus.UNAUTHORIZED.getCode());
            map.put("msg","无效的token");
        } else {
            //没有携带token
            map.put("code",HttpStatus.UNAUTHORIZED.getCode());
            map.put("msg","访问此资源需要完全的身份验证");
        }
        map.put("data",authException.getMessage());
        map.put("success",false);
        map.put("path",req.getServletPath());
        map.put("timestamp",String.valueOf(System.currentTimeMillis()));
        res.setContentType("application/json;charset=UTF-8");
        res.setStatus(HttpStatus.UNAUTHORIZED.getCode());
        ObjectMapper objectMapper = new ObjectMapper();
        //数据直接写入到输出流中
        objectMapper.writeValue(res.getOutputStream(),map);

    }
}
